1
Local Scope and Automatic Object Lifetimes
AI037 Lesson 9
00:00

In the grand theater of a C++ program, objects are like actors. Some stay on stage for the whole play, but most—the local objects—are ephemeral entities that appear for a single scene and vanish forever. This lesson establishes the fundamental distinction between an object's visibility (Scope) and its existence (Lifetime).

1. Lexical Scope vs. Execution Lifetime

The Scope of a name is a compile-time property: it is the region of the program text where a name is usable. Conversely, Lifetime is a run-time property: the duration for which the object occupies a physical memory address.

Source Code (Scope) { int i = 42; cout << i; } Memory Stack (Lifetime) i: 42 Other Frames Instantiation Block Exit / Pop

2. Automatic Objects

Objects that exist only while a block is executing are automatic objects. They are created when control passes through their definition (int n = 0;) and destroyed when the closing brace (}) is reached. Parameters are effectively local variables initialized by arguments.

main.py
TERMINAL bash — 80x24
> Ready. Click "Run" to execute.
>